<script setup>
import { postFileApi } from "@/api/file"
import { useRoute,useRouter } from "vue-router";
import{getAllPostApi,getStatusPostApi,auditArticleApi} from '@/api/admin/article'
import{delArticleApi,modyfyArticleApi,} from '@/api/article'
import {postType,postStatus} from "@/utils/globleVar"
import { onMounted, reactive, ref, watch } from "vue";
import ArticleList from "@/components/admin/articleList.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import upImg from "@/components/upImg.vue";

const showArticleList = reactive({
  articleList:[],
  pageInfo:{}
})
const router = useRouter()
const route =useRoute()
const listType = ref('')
//为帖子列表设置初值
setArticleList(0)
async function setArticleList(index){
  try{
    const resp = await getAllPostApi(index)
    if(resp.data.code === 200){
        const articles = resp.data.data.content
        if(index === 0){
          showArticleList.articleList = []
        }
        if(articles.length !== 0){
          showArticleList.pageInfo = resp.data.data.page
          articles.forEach(post=>{
            showArticleList.articleList.push(post)
          })
        }
    } 
  }catch(e){
    console.log(e)
  }
}
//------------------------------------------------------------------
//获取 通过&未通过 的帖子列表 
const getAuditPosts =async ()=>{
  const respApproved = await getStatusPostApi(postStatus.approved,index.value)
  const respRejected = await getStatusPostApi(postStatus.rejected,index.value)
  const posts = []
  posts.push(respApproved.data.data.content)
  posts.push(respRejected.data.data.content)
  return posts
}

//筛选帖子列表类型
const value = ref('ALL')
watch(value,async (newValue)=>{
  switch(newValue){
    case 'ALL':
      const respAll = await getAllPostApi(0)
      if(respAll.data.code === 200){
        const allArticles = respAll.data.data.content
        showArticleList.articleList = []
        allArticles.forEach((article)=>{
          showArticleList.articleList.push(article)
        })
      }
      break
    case 'DRAFT':
      const respDraft = await getStatusPostApi(postStatus.draft,0)
      if(respDraft.data.code === 200){
        const draftArticles = respDraft.data.data.content
        showArticleList.articleList = []
        draftArticles.forEach((article)=>{
          showArticleList.articleList.push(article)
        })
      }
      break
    case 'APPROVED':
      const respApproved = await getStatusPostApi(postStatus.approved,0)
      if(respApproved.data.code === 200){
        const approvedArticles = respApproved.data.data.content
        showArticleList.articleList = []
        approvedArticles.forEach((article)=>{
          showArticleList.articleList.push(article)
        })
      }
      break
    case 'REJECTED':
      const respRejected = await getStatusPostApi(postStatus.rejected,0)
      if(respRejected.data.code === 200){
        const rejectedArticles = respRejected.data.data.content
        showArticleList.articleList = []
        rejectedArticles.forEach((article)=>{
          showArticleList.articleList.push(article)
        })
      }
      break
  }
})
//处理下拉框的选择
const handleCommand = async (command) => {
  value.value = command
  return
}
//获取相应类型得帖子的分页数据
const getArticlesByType =async (page)=>{
  var newListResp = []
  try{
    newListResp = await getAllPostApi(page)
  }catch(e){
    console.log(e)
  }
  if(value.value === postStatus.all){
    try{
      newListResp = await  getAllPostApi(page)
    }catch(e){
      console.log(e)
    }
  }
  if(value.value === postStatus.draft){
    try{
      newListResp = await  getStatusPostApi(postStatus.draft,page)
    }catch(e){
      console.log(e)
    }
  }
  if(value.value === postStatus.approved){
    try{
      newListResp = await  getStatusPostApi(postStatus.approved,page)
    }catch(e){
      console.log(e)
    }
  }
  if(value.value === postStatus.rejected){
    try{
      newListResp = await  getStatusPostApi(postStatus.rejected,page)
    }catch(e){
      console.log(e)
    }
  }
  return newListResp.data.data
}
//修改帖子审核状态
const updateStatus = async (articleId,status)=>{
  try{
    const resp = await auditArticleApi(articleId,status)
    if(resp.data.code === 200 && postStatus.approved === status){
      ElMessage.success('审核通过')
      const data =await getArticlesByType(0)
      showArticleList.articleList = []
      showArticleList.articleList = data.content
      showArticleList.pageInfo = data.page
    }
    if(resp.data.code === 200 && postStatus.rejected === status){
      ElMessage.success('帖子已驳回')
      const data = await getArticlesByType(0)
      showArticleList.articleList = []
      showArticleList.articleList = data.content
      showArticleList.pageInfo = data.page
    }
  }catch(e){
    ElMessage.warning('系统异常，请联系管理员')
    console.log(e)
  }
}

//---------删除帖子-----------------
const onClickDel = async (articleId)=>{
  ElMessageBox.confirm(
    '确认删除？',
    '警告',
    {
      confirmButtonText:'删除',
      cancelButtonText:'取消',
      type:'warning'
    }
  ).then( async()=>{
      try{
      //发送审核请求
      const resp = await delArticleApi(articleId)
      if(resp.data.code == 200 ){
         setArticleList(0)
          ElMessage.success('删除成功')
      }
      }catch(e){
          console.log(e)
          ElMessage.error(e.message)
      }
    }).catch(()=>{
      
    })
}
//-------------------编辑帖子-----------------
const showPost = ref()
const showUpdataBox = ref(false)
const onClickEdit = (post)=>{
  showUpdataBox.value = true
  showPost.value = post
}
//移除旧图片
const delImg = (id)=>{
  const imgsUrl = showPost.value.images
  imgsUrl.forEach((img,index)=>{
      if(img.id === id){
          imgsUrl.splice(index,1)
      }
  })
  showPost.value.images = imgsUrl
}
//添加新图片
const imgFile = ref(FileList)
const onUpload = (imgFiles)=>{
    imgFile.value = imgFiles
}
//移除新图片
const removeImg = (id)=>{
  imgFile.value.forEach((img,index)=>{
      if(img.uid === id){
          imgFile.value.splice(index,1)
      }
  })
}
//取消更新 
const onCancle = ()=>{
  showUpdataBox.value = false
}
//确认更新
const onUpdate = async (imgFiles)=>{
    //构造请求数据
    const updatePostForm={
      id:showPost.value.id,
      title:showPost.value.title,
      content:showPost.value.content,
      images:[],
      status:postStatus.draft
    }
    //处理旧图片 
    const imageUrlArr = showPost.value.images
    imageUrlArr.forEach((oldImg)=>{
      //构造图片信息
      const img = {
        post_id:showPost.value.id,
       image_url:oldImg.imageUrl
      }
      updatePostForm.images.push(img)
    })
    //处理新图片
    try{
      if(imgFile.value.length !== 0){
          const uploadPromises = imgFile.value.map((file) =>
          postFileApi(file).then((respUpImg) => ({
            post_id:showPost.value.id,
            image_url: respUpImg.data.data[0],
          }))
          );
          // 等待所有图片上传完成
          const newImages = await Promise.all(uploadPromises);
          newImages.forEach(img=>{
            updatePostForm.images.push(img)
          })
      }
    }catch(e){
      console.log(e)
      ElMessage.error('上传图片异常')
    }
    //发送更新请求
    try{
      const resp = await modyfyArticleApi(updatePostForm)
      if(resp.data.code === 200){
        ElMessage.success('文章更新成功，待审核')
        showUpdataBox.value = false
        imgFile.value = []
        const resp = await getArticlesByType(0)
        showArticleList.articleList = resp.content
        showArticleList.pageInfo = resp.page
      }
    }catch(e){
    ElMessage.error('文章更新异常')
    console.log(e)
    }
}

//获取下一页数据
const getMoreArticle = async (pageInfo)=>{
  if(pageInfo.totalPages === 1 || pageInfo.number+1 >= pageInfo.totalPages){
        return
    }else{
        setArticleList(pageInfo.number+1)
    } 
}
</script>
<template>
  <div class="article-box">
    <!-- 下拉菜单 控制获取 所有/已审核  -->
    <el-select
      class="select"
      v-model="listType"
      :change="handleCommand(listType)"
      placeholder="类型选择"
      size="large"
      style="width: 120px">
      <el-option
        v-for="item in postType"
        :key="item.tyep"
        :label="item.name"
        :value="item.tyep"
      />
    </el-select>
    <!-- 帖子更新弹出框 -->
    <el-dialog
      title="修改文章"
      v-model="showUpdataBox">
      <el-form>
          <el-form-item>
              <span>标题:</span>
              <el-input
              clearable
              placeholder="请输标题"
              v-model="showPost.title"
              ></el-input>
          </el-form-item>
          <el-form-item>
              <span>内容:</span>
              <el-input
              clearable
              placeholder="请输入内容"
              v-model="showPost.content"
              ></el-input>
          </el-form-item>
          <div class="imgs" v-for="(img,index) in showPost.images" :key="index">
              <el-icon
              @click="delImg(img.id)"
              ><CloseBold /></el-icon>
              <img class="img" :src="img.imageUrl">
          </div>
          <upImg
          :showConfirm="true"
          @onUpload="onUpload"
          @onUpdate="onUpdate"
          @removeImg="removeImg"
          ></upImg>
          <el-form-item>
               <el-button
               @click="onCancle">
                  取消
              </el-button>
          </el-form-item>
      </el-form> 
    </el-dialog>
    <!-- 帖子列表-->
    <ArticleList
    class="articleList"
    @updateStatus="updateStatus"
    @clickEdit="onClickEdit"
    @clickDel="onClickDel"
    @loadMore="getMoreArticle"
    :articleInfo="showArticleList"
    ></ArticleList>
  </div>
</template>

<style lang="scss" scoped>
.article-box{
  width: 100%;
  height: 100%;
.el-dialog{
  .el-form{
      .el-form-item{
      }
      .imgs{
          .img{
              width: 200px;
              height: 200px;
          }
      }
  }
}
.articleList{
  width: 100%;
}
::-webkit-scrollbar{
  display: none;
}
}

</style>